package com.mall.project.sys.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.common.core.utils.LocalDateTimeUtils;
import com.mall.project.info.model.entity.Photo;
import com.mall.project.info.service.IPhotoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 图片调度器
 */
@Slf4j
@Component
public class PhotoTask {

    @Autowired
    private IPhotoService photoService;

    /**
     * 定时清除图片
     *
     * @param days n天前的图片
     */
    public void doClear(Integer days) {
        List<Photo> photos = photoService.list(new LambdaQueryWrapper<Photo>()
                .lt(Photo::getCreateTime, LocalDateTimeUtils.minu(LocalDateTime.now(), days, ChronoUnit.DAYS))
                .in(Photo::getStatus, "临时", "失效"));
        for (Photo photo : photos) {
            photoService.deletePhoto(photo.getBucket(), photo.getUrl());
            photoService.removeById(photo.getPhotoId());
        }
        log.info("PhotoTask.clear 定时清除图片 数量：{} ", photos.size());
    }

}
